package com.shenmazong.serverdemoes.util;

import com.shenmazong.serverdemoes.pojo.TbProduct;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 田不平
 * @project server-security
 * @date 2020/4/13 2:00 PM
 * http://www.shenmazong.com
 */
public class UtilHtmlParser {

    public static void main(String[] args) {
        UtilHtmlParser utilHtmlParser = new UtilHtmlParser();
        utilHtmlParser.getJdHtml("vue");
    }

    public List<TbProduct> getJdHtml(String keyword) {
        List<TbProduct> products = new ArrayList();

        try {
            // 获取请求 https://search.jd.com/Search?keyword=java
            String url = "https://search.jd.com/Search?keyword=" + keyword;

            // Jsoup 返回的Document就是浏览器Document对象
            Document document = Jsoup.parse(new URL(url), 3000);

            Element element = document.getElementById("J_goodsList");

            // 获取所有li元素
            Elements elements = element.getElementsByTag("li");

            // 遍历每个li元素
            for(Element el : elements) {

                // source-data-lazy-img
                //System.out.println(el.getElementsByClass("p-img").html());

                String price = el.getElementsByClass("p-price").first().getElementsByTag("i").text();
                String img = el.getElementsByTag("img").eq(0).attr("source-data-lazy-img");
                String title = el.getElementsByClass("p-name").eq(0).text();

                //
                TbProduct product = new TbProduct(title, price, img);
                products.add(product);

                System.out.println(product);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return products;
    }



}
